//---------------------------------------------------------------------------------
// Copyright (c) 2011, Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//---------------------------------------------------------------------------------


namespace Microsoft.Samples.MessagingWithQueues
{
    using System;
    using System.Collections.Generic;
    using Microsoft.ServiceBus;
    using Microsoft.ServiceBus.Messaging;

    public class Sender
    {
        const string QueueName = "IssueTrackingQueue";
        static string ServiceNamespace;
        static string IssuerName;
        static string IssuerKey;

        static void Main(string[] args)
        {
            GetUserCredentials();    
            TokenProvider credentials = TokenProvider.CreateSharedSecretTokenProvider(Sender.IssuerName, Sender.IssuerKey);
            Uri serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", Sender.ServiceNamespace, string.Empty);

            MessagingFactory factory = null;

            try
            {
                //*****************************************************************************************************
                //                                   Management Operations
                //*****************************************************************************************************           
                NamespaceManager namespaceClient = new NamespaceManager(serviceUri, credentials);
                if (namespaceClient == null)
                {
                    Console.WriteLine("\nUnexpected Error: NamespaceManager is NULL");
                    return;
                }

                Console.WriteLine("\nCreating Queue '{0}'...", Sender.QueueName);

                // Delete if exists
                if (namespaceClient.QueueExists(Sender.QueueName))
                {
                    namespaceClient.DeleteQueue(Sender.QueueName);
                }

                namespaceClient.CreateQueue(Sender.QueueName);

                //*****************************************************************************************************
                //                                   Runtime Operations
                //*****************************************************************************************************
                factory = MessagingFactory.Create(serviceUri, credentials);

                QueueClient myQueueClient = factory.CreateQueueClient(Sender.QueueName);

                //*****************************************************************************************************
                //                                   Sending messages to a Queue
                //*****************************************************************************************************
                List<BrokeredMessage> messageList = new List<BrokeredMessage>();

                messageList.Add(CreateIssueMessage("1", "First message information"));
                messageList.Add(CreateIssueMessage("2", "Second message information"));
                messageList.Add(CreateIssueMessage("3", "Third message information"));

                Console.WriteLine("\nSending messages to Queue...");

                foreach (BrokeredMessage message in messageList)
                {
                    myQueueClient.Send(message);
                    Console.WriteLine(string.Format("Message sent: Id = {0}, Body = {1}", message.MessageId, message.GetBody<string>()));
                }

                Console.WriteLine("\nAfter running the entire sample, press ENTER to clean up and exit.");
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine("Unexpected exception {0}", e.ToString());
                throw;
            }
            finally
            {
                // Closing factory close all entities created from the factory.
                if(factory != null)
                    factory.Close();
            }
            
        }

        static void GetUserCredentials()
        {
            Console.Write("Please provide the service namespace to use: ");
            ServiceNamespace = Console.ReadLine();

            Console.Write("Please provide the issuer name to use: ");
            IssuerName = Console.ReadLine();

            Console.Write("Please provide the issuer key to use: ");
            IssuerKey = Console.ReadLine();
        }

        private static BrokeredMessage CreateIssueMessage(string issueId, string issueBody)
        {            
            BrokeredMessage message = new BrokeredMessage(issueBody);
            message.MessageId = issueId;

            return message;
        }
    }
}
